package com.xywy.bloodandroid.fragment;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.reflect.TypeToken;
import com.xywy.bloodandroid.R;
import com.xywy.bloodandroid.act.HosptailLevelAct;
import com.xywy.bloodandroid.act.LoginAct;
import com.xywy.bloodandroid.act.QuestionListAct;
import com.xywy.bloodandroid.act.SearchAct;
import com.xywy.bloodandroid.act.SelectorDoctorAct;
import com.xywy.bloodandroid.act.SetDocotrHonorAct;
import com.xywy.bloodandroid.act.SetProvinceAct;
import com.xywy.bloodandroid.adapter.HotDoctotAdapter;
import com.xywy.bloodandroid.base.BaseFragment;
import com.xywy.bloodandroid.bean.HotDoctorInfo;
import com.xywy.bloodandroid.bean.User;
import com.xywy.bloodandroid.custom.MyGridView;
import com.xywy.bloodandroid.util.Constants;
import com.xywy.bloodandroid.util.JsonUtil;
import com.xywy.bloodandroid.util.UIUtil;
import com.xywy.bloodandroid.vollery.GetRequest;
import com.xywy.bloodandroid.vollery.OnVolleyResponseListener;

/**
 * *****************************************
 * 
 * @Title: DoctorOnlineFragment.java
 * @Package com.xywy.bloodandroid.fragment
 * @Description: TODO(医生在线)
 * @author smz
 * @date 2014-12-23 下午2:01:39
 * @version V1.0
 ******************************************* 
 */
public class DoctorOnlineFragment extends BaseFragment implements
		OnClickListener {
	private TextView online_doctor_number;
	private RelativeLayout li_province;
	private TextView chance_province_text;
	private ImageView mylocation;
	private RelativeLayout doctor_honor;
	private TextView tv_doctor_honor_text;
	private RelativeLayout hosptail_level;
	private TextView tv_hosptail_level;
	private RelativeLayout rl_screen_result;
	private TextView tv_screen_result;
	private ImageView is_doctor_plus;
	private Button query_doctor;
	private TextView ask_doctor;
	private TextView phone_doctor;
	private MyGridView grid_view;
	private TextView change_doctor;
	private RelativeLayout left_img;
	private TextView middle_title;

	private int pageCount = 4;// 每页显示的条数
	private int PageNum = 1;// 页码
	private List<HotDoctorInfo> templsit;
	private HotDoctotAdapter adapter;

	private int num = 1;// 记录是否点击加号
	private RelativeLayout is_doctor_plus_rel;
	private ScrollView scrollview;
	private int is_plus;
	private int pageNum = 1;

	private boolean flag = true;

	// 定位相关
	LocationClient mLocClient;
	public MyLocationListenner myListener = new MyLocationListenner();
	Handler handler = new Handler() {
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_doctor_online, null);

		initView(view);
		initListener();
		initdata();

		return view;
	}

	private void initView(View view) {

		left_img = (RelativeLayout) view.findViewById(R.id.left_img);
		left_img.setVisibility(View.GONE);

		middle_title = (TextView) view.findViewById(R.id.middle_title);
		middle_title.setText(R.string.doctor_online);

		scrollview = (ScrollView) view.findViewById(R.id.scrollview);

		online_doctor_number = (TextView) view
				.findViewById(R.id.online_doctor_number);
		li_province = (RelativeLayout) view.findViewById(R.id.li_province);
		chance_province_text = (TextView) view
				.findViewById(R.id.chance_province_text);
		mylocation = (ImageView) view.findViewById(R.id.mylocation);
		doctor_honor = (RelativeLayout) view.findViewById(R.id.doctor_honor);
		tv_doctor_honor_text = (TextView) view
				.findViewById(R.id.tv_doctor_honor_text);
		hosptail_level = (RelativeLayout) view
				.findViewById(R.id.hosptail_level);
		tv_hosptail_level = (TextView) view
				.findViewById(R.id.tv_hosptail_level);
		rl_screen_result = (RelativeLayout) view
				.findViewById(R.id.rl_screen_result);
		tv_screen_result = (TextView) view.findViewById(R.id.tv_screen_result);
		is_doctor_plus = (ImageView) view.findViewById(R.id.is_doctor_plus);
		query_doctor = (Button) view.findViewById(R.id.query_doctor);
		ask_doctor = (TextView) view.findViewById(R.id.ask_doctor);
		phone_doctor = (TextView) view.findViewById(R.id.phone_doctor);

		grid_view = (MyGridView) view.findViewById(R.id.grid_view);

		change_doctor = (TextView) view.findViewById(R.id.change_doctor);

		is_doctor_plus_rel = (RelativeLayout) view
				.findViewById(R.id.is_doctor_plus_rel);

		no_data_text = (TextView) view.findViewById(R.id.no_data_text);

	}

	private void initListener() {
		li_province.setOnClickListener(this);
		mylocation.setOnClickListener(this);
		doctor_honor.setOnClickListener(this);
		hosptail_level.setOnClickListener(this);
		rl_screen_result.setOnClickListener(this);
		// is_doctor_plus.setOnClickListener(this);
		is_doctor_plus_rel.setOnClickListener(this);
		query_doctor.setOnClickListener(this);
		ask_doctor.setOnClickListener(this);
		phone_doctor.setOnClickListener(this);
		change_doctor.setOnClickListener(this);
	}

	private void initdata() {

		templsit = new ArrayList<HotDoctorInfo>();
		adapter = new HotDoctotAdapter(getActivity(), templsit);
		grid_view.setAdapter(adapter);
		 getHotDoctorInfo();
	}

	/**
	 * 热门专家
	 */
	private void getHotDoctorInfo() {
		GetRequest<String> getRequest = new GetRequest<String>(
				Constants.getUrl("zhuanjia", "HotDoctor") + "&pageNum="
						+ pageNum + "&pageCount=4", String.class,
				new OnVolleyResponseListener<String>() {

					@Override
					public void onError(VolleyError volleyError) {
						UIUtil.DissDialog(getActivity(), waittingDialog);
						UIUtil.showToast(getActivity(), getActivity()
								.getString(R.string._slow_intet));
						no_data_text.setVisibility(View.VISIBLE);
						flag = true;
					}

					@SuppressWarnings("unchecked")
					@Override
					public void onSuccess(String response) {
						flag = true;
						UIUtil.DissDialog(getActivity(), waittingDialog);
						JSONObject object;
						try {
							object = new JSONObject(response);

							int code = object.getInt("code");
							String msg = object.getString("msg");
							String data = object.getString("data");
							int total = object.getInt("total");
							if (code == 10000) {

								online_doctor_number.setText("全国有" + total
										+ "位血压专家为您在线治疗");
								List<HotDoctorInfo> tempData = (List<HotDoctorInfo>) JsonUtil
										.parseJsonToList(
												data,
												new TypeToken<List<HotDoctorInfo>>() {
												}.getType());
								templsit.addAll(tempData);
								adapter.notifyDataSetChanged();
								scrollview.smoothScrollTo(0, 0);// scrollview里嵌套自定义listview时不显示到顶部的设置
								if (templsit.size() < 1) {
									no_data_text.setVisibility(View.VISIBLE);
								}
								System.out.println("获取的...." + templsit.size());
							} else {
								UIUtil.showToast(getActivity(), msg);
							}
						} catch (JSONException e) {
							UIUtil.showToast(getActivity(), getActivity()
									.getString(R.string.error_data));
							e.printStackTrace();
						}
					}
				});
		getRequest.setIsParseJson(false);
		executeRequest(getRequest);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		System.out.println("sahdfsjhkg");
		handler.postDelayed(new Runnable() {

			@Override
			public void run() {
				scrollview.scrollTo(0, 0);
			}
		}, 100);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.li_province:
			Intent intent1 = new Intent(getActivity(), SetProvinceAct.class);
			startActivityForResult(intent1, 3);

			break;
		case R.id.mylocation:
			LocationCreateDialog();
			break;
		case R.id.doctor_honor:
			Intent intent3 = new Intent(getActivity(), SetDocotrHonorAct.class);
			startActivityForResult(intent3, 1);
			break;
		case R.id.hosptail_level:
			Intent intent2 = new Intent(getActivity(), HosptailLevelAct.class);
			startActivityForResult(intent2, 0);

			break;
		case R.id.rl_screen_result:
			Intent intent4 = new Intent(getActivity(), SearchAct.class);
			startActivityForResult(intent4, 2);
			break;
		case R.id.is_doctor_plus_rel:
			System.out.println("获取的 是否加号的判断..." + num % 2);
			is_plus = num % 2;// 1是可预约 0不可预约
			if (is_plus != 0) {
				is_doctor_plus.setBackgroundResource(R.drawable.checkbox_press);
				IsPlus = "1";
			} else {
				is_doctor_plus
						.setBackgroundResource(R.drawable.checkbox_normal);
				IsPlus = "0";
			}
			num++;

			break;
		case R.id.query_doctor:
			Intent intent5 = new Intent(getActivity(), SelectorDoctorAct.class);

			if ("不限".equals(province)) {
				intent5.putExtra("province", "");//
			} else {
				intent5.putExtra("province", province);//
			}
			intent5.putExtra("title", title);// 医生职称
			intent5.putExtra("keyword", keyword);// 关键字的查询
			intent5.putExtra("level ", level);
			intent5.putExtra("IsPlus", IsPlus);
			startActivity(intent5);
			break;
		case R.id.phone_doctor:
			createDialog();
			break;
		case R.id.ask_doctor:
			if (User.getInstance(getActivity()).getUserid().length() < 1) {
				UIUtil.showToast(getActivity(), "请先登录~");
				Intent intent = new Intent(getActivity(), LoginAct.class);
				startActivity(intent);
			} else {
				Intent intent = new Intent(getActivity(), QuestionListAct.class);
				getActivity().startActivity(intent);
			}

			break;
		case R.id.change_doctor:
			// Intent intent6=new Intent(getActivity(), TheIllnessAct.class);
			// getActivity().startActivity(intent6);
			if (flag) {
				pageNum++;
				templsit.clear();
				getHotDoctorInfo();
				flag = false;
			} else {
				// UIUtil.showToast(getActivity(), "操作过快"); 防止点击过于频繁
				flag = false;
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 电话定位
	 */
	private void LocationCreateDialog() {
		Dialog dialog = new AlertDialog.Builder(getActivity())
				.setTitle("温馨提示")
				.setMessage("您是否允许健康血压使用定位功能.")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {

						// 定位初始化
						mLocClient = new LocationClient(getActivity());
						mLocClient.registerLocationListener(myListener);

						LocationClientOption option = new LocationClientOption();
						option.setOpenGps(true);// 打开gps
						option.setCoorType("bd09ll"); // 设置坐标类型
						option.setAddrType("all");
						option.setScanSpan(1000);
						mLocClient.setLocOption(option);
						mLocClient.start();
						
						   waitingDialog(getActivity(), "正在定位");
						
						
					
						

					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						if (mLocClient != null)
							mLocClient.stop();
					}
				}).create();
		// 显示提示框
		dialog.show();
	}

	/**
	 * 打电话的对话框
	 */
	private void createDialog() {
		Dialog dialog = new AlertDialog.Builder(getActivity())
				.setTitle("温馨提示")
				.setMessage("您是否要拨打寻医问药的健康电话:400-9700-120")
				// 400—889-6550
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent(Intent.ACTION_DIAL, Uri
								.parse("tel://400-9700-120"));
						startActivity(intent);

					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					}
				}).create();
		// 显示提示框
		dialog.show();
	}

	/**
	 * 通过条件查询医生
	 */
	private String level;// 医院等级
	private String IsPlus = "0";// 是否加号 1是加号 0是
	private String province;
	private String title;// 主任医师
	private String keyword;// 搜索的关键字
	private TextView no_data_text;

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(data!=null){
		switch (requestCode) {
		case 0:
			String value;
			value = data.getStringExtra("doctor_level_name");
			if (value != null)
				tv_hosptail_level.setText(value);
			level=value;
			break;
		case 1:
			String value1;
			value1 = data.getStringExtra("doctor_level_name");
			if (value1!= null)
				tv_doctor_honor_text.setText(value1);
			if(value1.equals("不限")){
				title="";
			}else{
				
				title=value1;
			}
			break;
		case 2:
			String value2;
			value2 = data.getStringExtra("serach_act");
			if (value2.length()>0)
				tv_screen_result.setText(value2);
			else
				tv_screen_result.setText(R.string.search_text);
			keyword=value2;
			break;
		case 3:
			String value3;
			value3 = data.getStringExtra("province");
			if (value3.length()>0)
				chance_province_text.setText(value3);
			else
				chance_province_text.setText("省份");
			province=value3;
			break;
			
		default:
			break;
		}
		}
	}

	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {

        
			if (location == null )
				return;
		     
			  
			Province = location.getProvince();
			
			if(Province!=null){
				if (waittingDialog!=null&&waittingDialog.isShowing()) {
					waittingDialog.dismiss();
				}
				UIUtil.showToast(getActivity(), "定位成功");
				chance_province_text.setText(Province);
				// 退出时销毁定位
				mLocClient.stop();
				province=Province;
				System.out.println("获取的省份是哪里呢..."+province);
			}
		}

		public void onReceivePoi(BDLocation poiLocation) {
		}
	}

	@Override
	public void onDestroy() {
		// 退出时销毁定位
		if(mLocClient!=null&&mLocClient.isStarted())
	    mLocClient.stop();
	    super.onDestroy();
	}

	private String Province;
}